from django.core.mail import send_mail
from users.models import EmailVerifyCode
from random import choice
from django.conf import settings


def send_mail_code(email, send_type):
    # 创建邮箱验证码对象,保存数据库,用来以后做对比
    code = get_random_code(8)
    ev = EmailVerifyCode()
    ev.email = email
    ev.send_type = send_type
    ev.code = code
    ev.save()
    # 发邮件
    if send_type == 1:
        send_title = '欢迎注册谷粒教育网站'
        send_body = '请点击以下链接进行激活您的账号:\n http://127.0.0.1:8000/users/user_active/' + code
        send_mail(send_title, send_body, settings.EMAIL_FROM, [email])
    elif send_type == 2:
        send_title = '谷粒教育重置密码'
        send_body = '请点击以下链接进行重置或者修改密码:\n http://127.0.0.1:8000/users/user_reset/' + code
        send_mail(send_title, send_body, settings.EMAIL_FROM, [email])
    elif send_type == 3:
        send_title = '谷粒教育修改邮箱验证码'
        send_body = '您的验证码是:' + code
        send_mail(send_title, send_body, settings.EMAIL_FROM, [email])


def get_random_code(code_length):
    code_source = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    code = ''
    for i in range(code_length):
        code += choice(code_source)
    return code
